package cc.admin.modules.graduate.service.impl;

import cc.admin.common.es.ElasticsearchTemplate;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.common.util.RestUtil;
import cc.admin.modules.graduate.entity.UserForumLike;
import cc.admin.modules.graduate.mapper.UserForumLikeMapper;
import cc.admin.modules.graduate.service.IUserForumLikeService;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户评论点赞表
 * @Author: cc-admin
 * @Date: 2025-02-26
 * @Version: V1.0.0
 */
@Service
public class UserForumLikeServiceImpl extends ServiceImpl<UserForumLikeMapper, UserForumLike> implements IUserForumLikeService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private UserForumLikeMapper userForumLikeMapper;

    @Override
    @Transactional
    public void saveLike(UserForumLike like) {
        String indexName = "like_index";
        String typeName = "like_type";
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String id = checkExists(indexName, typeName, like.getUserId(), like.getForumId());
        if (id!=null&&!id.equals("")) {
            System.out.println("相同的 userId 和 forumId 记录已存在，不进行添加。");
            System.out.println(getLikedForumLikesByUserId(like.getUserId()));
            System.out.println(countUserIdByForumId());
//            elasticsearchTemplate.delete(indexName, typeName, like.getId());
            // 方式一：使用 delete 方法
            String deleteUrl = "http://127.0.0.1:9200" + "/" + indexName + "/_doc/" + id;
            JSONObject deleteResult = RestUtil.delete(deleteUrl);
            LambdaQueryWrapper<UserForumLike> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserForumLike::getForumId,like.getForumId());
            queryWrapper.eq(UserForumLike::getUserId,user.getUsername());
            userForumLikeMapper.delete(queryWrapper);
            return;
        }

        if (like.getId() == null) {
            like.setId(UuidUtils.getUUID());
        }

        // 将实体类转换为JSONObject
        com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSON.toJSONString(like));

        boolean result = elasticsearchTemplate.saveOrUpdate(indexName, typeName, like.getId(), data);
        userForumLikeMapper.insert(like);
        if (result) {
            System.out.println("点赞数据保存成功");
        } else {
            System.out.println("点赞数据保存失败");
        }
    }

    @Override
    public List<UserForumLike> getLikedForumLikesByUserId(String userId) {
        String indexName = "like_index";
        String typeName = "like_type";

        // 构建查询字符串
        JSONObject queryString = elasticsearchTemplate.buildQueryString("userId", userId);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(queryString);

        // 构建布尔查询
        JSONObject query = elasticsearchTemplate.buildBoolQuery(jsonArray, null, null);

        // 修改 buildQuery 方法调用，确保查询语句格式正确
        JSONObject searchQuery = elasticsearchTemplate.buildQuery(null, query, 0, ElasticsearchTemplate.ES_MAX_SIZE);

        // 执行搜索
        JSONObject result = elasticsearchTemplate.search(indexName, typeName, searchQuery);
        JSONArray hits = result.getJSONObject("hits").getJSONArray("hits");

        // 处理搜索结果
        List<UserForumLike> likes = new ArrayList<>();
        for (Object hitObj : hits) {
            JSONObject hit = JSONObject.parseObject(JSONObject.toJSONString(hitObj));
            JSONObject source = hit.getJSONObject("_source");
            UserForumLike like = com.alibaba.fastjson.JSONObject.parseObject(source.toJSONString(), UserForumLike.class);
            likes.add(like);
        }

        return likes;
    }

    public JSONObject countUserIdByForumId() {
        String indexName = "like_index";
        String typeName = "like_type";

        // 构建聚合查询
        JSONObject aggregation = new JSONObject();
        JSONObject termsAggregation = new JSONObject()
                .fluentPut("field", "forumId")
                .fluentPut("size", 5)
                .fluentPut("order", new JSONObject().fluentPut("distinct_users.value", "desc"));

        JSONObject groupByForumIdAggregation = new JSONObject()
                .fluentPut("terms", termsAggregation)
                .fluentPut("aggs", new JSONObject()
                        .fluentPut("distinct_users", new JSONObject()
                                .fluentPut("cardinality", new JSONObject()
                                        .fluentPut("field", "userId"))));

        aggregation.put("group_by_forum_id", groupByForumIdAggregation);

        // 构建完整的查询对象，使用 match_all 查询所有文档
        JSONObject matchAllQuery = new JSONObject();
        matchAllQuery.put("match_all", new JSONObject());
        JSONObject query = new JSONObject();
        query.put("query", matchAllQuery);
        query.put("aggs", aggregation);
        query.put("size", 0); // 不返回实际文档，只返回聚合结果

        // 执行查询
        JSONObject result = elasticsearchTemplate.search(indexName, typeName, query);

        return result.getJSONObject("aggregations");
    }

    private String checkExists(String indexName, String typeName, String userId, String forumId) {
        JSONObject queryString = elasticsearchTemplate.buildQueryString("userId", userId);
        JSONArray mustArray = new JSONArray();
        mustArray.add(queryString);
        JSONObject queryString2 = elasticsearchTemplate.buildQueryString("forumId", forumId);
        mustArray.add(queryString2);
        JSONObject query = elasticsearchTemplate.buildBoolQuery(mustArray, null, null);
        JSONObject searchQuery = elasticsearchTemplate.buildQuery(null, query, 0, 1);

        JSONObject result = elasticsearchTemplate.search(indexName, typeName, searchQuery);
        JSONArray hits = result.getJSONObject("hits").getJSONArray("hits");
        Object object = hits.get(0);
        String jsonString = JSONObject.toJSONString(object);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        String id = jsonObject.getString("_id");
        return id;
    }
}
